<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<html>
<head>
    <title>发货单管理</title>
    <meta charset="UTF-8">
    <base href="<%=request.getContextPath()%>/">
    <!-- 引入 EasyUI 的默认主题样式 -->
    <link rel="stylesheet" type="text/css" href="static/js/easyui/themes/bootstrap/easyui.css">
    <!-- 引入 EasyUI 的图标样式 -->
    <link rel="stylesheet" type="text/css" href="static/js/easyui/themes/icon.css">
    <!-- 引入自定义的公共CSS -->
    <link rel="stylesheet" type="text/css" href="static/css/common.css"/>
    <!-- 引入 EasyUI 默认的 jQuery -->
    <script src="static/js/easyui/jquery.min.js"></script>
    <!-- 引入 EasyUI 的核心 JS 文件 -->
    <script src="static/js/easyui/jquery.easyui.min.js"></script>
    <!-- 引入 EasyUI 的中文语言包 -->
    <script src="static/js/easyui/locale/easyui-lang-zh_CN.js"></script>
    <!-- 引入自定义的公共脚本 -->
    <script src="static/js/owner/common.js"></script>
    <script src="static/js/owner/dataGrid.js"></script>
    <script src="static/js/owner/moment.min.js"></script>
    <!-- 引入 doT 模板引擎 -->
    <script src="static/js/owner/doT.min.js"></script>
    <!-- daterangepicker 插件 -->
    <link rel="stylesheet" href="static/css/daterangepicker.css">
    <script src="static/js/owner/daterangepicker.js"></script>
    <style>
        /* 发货单状态标签样式 */
        .status-tag {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 3px;
            font-size: 12px;
            color: white;
        }
        .status-info { background-color: #2db7f5; }
        .status-success { background-color: #5cb85c; }
        .status-warning { background-color: #f0ad4e; }
        .status-primary { background-color: #337ab7; }
        .status-danger { background-color: #d9534f; }

        /* 发货单详情表格样式 */
        .shipment-details-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }
        .shipment-details-table th, .shipment-details-table td {
            padding: 8px;
            text-align: left;
            border: 1px solid #ddd;
        }
        .shipment-details-table th {
            background-color: #f5f5f5;
            font-weight: bold;
        }
        .shipment-details-table tbody tr:hover {
            background-color: #f9f9f9;
        }
        .searchDiv {
            display: flex;
            flex-direction: row;
            gap: 20px;
            margin: 20px 10px 5px 10px;
            flex-wrap: wrap;
        }
        .operationBtn {
            margin-top: 20px;
            margin-bottom: 10px;
        }
        .item {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .daterange {
            width: 220px !important;
        }
    </style>
</head>
<body>
    <!-- 搜索区域 -->
    <div class="searchDiv">
        <form id="searchForm">
            <div class="item">
                <label>发货单号:</label>
                <input class="easyui-textbox" id="shipmentNo" style="width:150px;">
                <label>订单号:</label>
                <input class="easyui-textbox" id="orderNo" style="width:150px;">
                <label>发货状态:</label>
                <select class="easyui-combobox" id="status" style="width:100px;" panelHeight="auto">
                    <option value="">全部</option>
                    <option value="0">待发货</option>
                    <option value="1">已发货</option>
                </select>
                <label>日期范围:</label>
                <input class="easyui-textbox daterange" id="dateRange">
                <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-search" onclick="searchData()">查询</a>
                <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-reload" onclick="resetSearch()">重置</a>
            </div>
        </form>
    </div>

    <!-- 工具栏 -->
    <div id="toolbar">
        <div class="operationBtn">
            <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-reload" plain="true" onclick="reloadData()">刷新</a>
        </div>
    </div>

    <!-- 数据表格 -->
    <table id="datagrid" class="easyui-datagrid">
        <thead>
            <tr>
                <th data-options="field:'shipmentNo',width:120,align:'center'">发货单号</th>
                <th data-options="field:'orderNo',width:120,align:'center'">关联订单号</th>
                <th data-options="field:'contactName',width:100,align:'center'">收件人</th>
                <th data-options="field:'contactPhone',width:120,align:'center'">联系电话</th>
                <th data-options="field:'shippingAddress',width:200,align:'left'">收货地址</th>
                <th data-options="field:'status',width:70,align:'center',formatter:formatStatus">状态</th>
                <th data-options="field:'createTime',width:150,align:'center'">创建时间</th>
                <th data-options="field:'shipTime',width:150,align:'center'">发货时间</th>
                <th data-options="field:'id',width:150,align:'center',formatter:formatOperation">操作</th>
            </tr>
        </thead>
    </table>

    <!-- 发货单详情对话框 -->
    <div id="shipmentDetailDlg" class="easyui-dialog" style="width:700px;height:450px;padding:10px 20px"
         data-options="closed:true,buttons:'#shipmentDetailDlg-buttons',modal:true,border:'thin',shadow:true">
        <div id="shipmentDetailContent"></div>
    </div>
    <div id="shipmentDetailDlg-buttons">
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="$('#shipmentDetailDlg').dialog('close')">关闭</a>
    </div>

    <!-- 确认发货对话框 -->
    <div id="confirmShipmentDlg" class="easyui-dialog" style="width:500px;height:320px;padding:10px 20px"
         data-options="closed:true,buttons:'#confirmShipmentDlg-buttons',modal:true,border:'thin',shadow:true">
        <div id="confirmShipmentContent"></div>
    </div>
    <div id="confirmShipmentDlg-buttons">
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onclick="confirmShipment()">确认发货</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="$('#confirmShipmentDlg').dialog('close')">取消</a>
    </div>

    <!-- 发货单详情模板 -->
    <script id="shipmentDetailTmpl" type="text/x-dot-template">
    <div class="shipment-detail">
        <h4>发货单基本信息</h4>
        <p><strong>发货单号：</strong>{{=it.shipmentNo}}</p>
        <p><strong>关联订单号：</strong>{{=it.orderNo}}</p>
        <p><strong>收件人：</strong>{{=it.contactName}}</p>
        <p><strong>联系电话：</strong>{{=it.contactPhone}}</p>
        <p><strong>收货地址：</strong>{{=it.shippingAddress}}</p>
        <p><strong>发货状态：</strong>{{=it.statusText}}</p>
        <p><strong>创建时间：</strong>{{=it.createTime}}</p>
        {{? it.shipTime }}<p><strong>发货时间：</strong>{{=it.shipTime}}</p>{{?}}

        <h4>发货商品明细</h4>
        <table class="shipment-details-table">
            <thead>
                <tr>
                    <th>商品名称</th>
                    <th>发货数量</th>
                    <th>发货仓库</th>
                </tr>
            </thead>
            <tbody>
                {{~it.shipmentItems :item:index}}
                <tr>
                    <td>{{=item.productName}}</td>
                    <td>{{=item.quantity}}</td>
                    <td>{{=item.warehouseName}}</td>
                </tr>
                {{~}}
            </tbody>
        </table>
    </div>
    </script>

    <!-- 确认发货模板 -->
    <script id="confirmShipmentTmpl" type="text/x-dot-template">
    <div class="shipment-confirm">
        <p><strong>发货单号：</strong>{{=it.shipmentNo}}</p>
        <p><strong>关联订单号：</strong>{{=it.orderNo}}</p>
        <p>确认发货以下商品：</p>
        <table class="shipment-details-table">
            <thead>
                <tr>
                    <th>商品名称</th>
                    <th>发货数量</th>
                    <th>发货仓库</th>
                </tr>
            </thead>
            <tbody>
                {{~it.shipmentItems :item:index}}
                <tr>
                    <td>{{=item.productName}}</td>
                    <td>{{=item.quantity}}</td>
                    <td>{{=item.warehouseName}}</td>
                </tr>
                {{~}}
            </tbody>
        </table>
    </div>
    </script>

    <script type="text/javascript">
        // 编译doT模板
        var shipmentDetailTmpl = doT.template($('#shipmentDetailTmpl').text());
        var confirmShipmentTmpl = doT.template($('#confirmShipmentTmpl').text());

        // 全局变量
        var currentShipment; // 当前操作的发货单

        $(function() {
            const pageConfig = {
                url: 'shipment/getData',
                method: 'get',
                emptyMsg: '暂无数据',
            };

            // 调用公共函数初始化 DataGrid
            initializeDataGrid(pageConfig);

            // 初始化日期范围选择器
            initializeDateRangePickers('.daterange');
        });

        // 初始化日期范围选择器
        function initializeDateRangePickers(selector) {
            $(selector).each(function() {
                $(this).textbox({
                    icons: [{
                        iconCls: 'icon-clear',
                        handler: function(e) {
                            $(e.data.target).textbox('clear');
                        }
                    }],
                    onChange: function(newValue, oldValue) {
                        // 日期变化时的处理逻辑
                    }
                });

                // 初始化日期范围选择器
                $(this).textbox('textbox').daterangepicker({
                    autoUpdateInput: false,
                    locale: {
                        cancelLabel: '清除',
                        applyLabel: '确定',
                        fromLabel: '从',
                        toLabel: '到',
                        customRangeLabel: '自定义',
                        weekLabel: 'W',
                        daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
                        monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
                        firstDay: 1
                    }
                });

                $(this).textbox('textbox').on('apply.daterangepicker', function(ev, picker) {
                    $(this).val(picker.startDate.format('YYYY-MM-DD') + ' 至 ' + picker.endDate.format('YYYY-MM-DD'));
                });

                $(this).textbox('textbox').on('cancel.daterangepicker', function(ev, picker) {
                    $(this).val('');
                });
            });
        }

        // 查询数据
        function searchData() {
            var formData = {};
            var dateRange = $('#dateRange').textbox('getValue');
            var startDate = null;
            var endDate = null;

            if (dateRange) {
                var dates = dateRange.split(' 至 ');
                if (dates.length === 2) {
                    startDate = dates[0];
                    endDate = dates[1];
                }
            }

            formData = {
                shipmentNo: $('#shipmentNo').textbox('getValue'),
                orderNo: $('#orderNo').textbox('getValue'),
                status: $('#status').combobox('getValue'),
                startDate: startDate,
                endDate: endDate
            };

            $('#datagrid').datagrid('load', formData);
        }

        // 重置搜索
        function resetSearch() {
            $('#searchForm').form('clear');
            $('#datagrid').datagrid('load', {});
        }

        // 刷新数据
        function reloadData() {
            $('#datagrid').datagrid('reload');
        }

        // 格式化发货状态
        function formatStatus(value, row) {
            var statusMap = {
                0: { text: '待发货', cls: 'status-warning' },
                1: { text: '已发货', cls: 'status-success' }
            };

            var status = statusMap[value] || { text: '未知', cls: '' };
            return '<span class="status-tag ' + status.cls + '">' + status.text + '</span>';
        }

        // 获取状态文本
        function getStatusText(status) {
            var statusMap = {
                0: '待发货',
                1: '已发货'
            };
            return statusMap[status] || '未知状态';
        }

        // 格式化操作列
        function formatOperation(value, row) {
            var btns = [];
            btns.push('<a href="javascript:void(0)" onclick="viewShipment(' + row.id + ')" class="easyui-linkbutton" iconCls="icon-search" plain="true">查看</a>');

            if (row.status === 0) {
                btns.push('<a href="javascript:void(0)" onclick="openConfirmShipment(' + row.id + ')" class="easyui-linkbutton" iconCls="icon-ok" plain="true">确认发货</a>');
            }

            return btns.join('');
        }

        // 在表格加载成功后渲染按钮
        $(function() {
            $('#datagrid').datagrid({
                onLoadSuccess: function() {
                    $('.easyui-linkbutton').linkbutton();
                }
            });
        });

        // 查看发货单详情
        function viewShipment(id) {
            $.ajax({
                url: 'shipment/detail/' + id,
                type: 'get',
                dataType: 'json',
                success: function(res) {
                    if (res.code === 200) {
                        var shipment = res.extend.shipment;
                        // 添加状态文本
                        shipment.statusText = getStatusText(shipment.status);

                        // 使用doT模板渲染发货单详情
                        var html = shipmentDetailTmpl(shipment);
                        $('#shipmentDetailContent').html(html);

                        $('#shipmentDetailDlg').dialog('open').dialog('setTitle', '发货单详情').window('center');
                    } else {
                        $.messager.alert('错误', res.msg || '获取发货单详情失败!', 'error');
                    }
                }
            });
        }

        // 打开确认发货对话框
        function openConfirmShipment(id) {
            $.ajax({
                url: 'shipment/detail/' + id,
                type: 'get',
                dataType: 'json',
                success: function(res) {
                    if (res.code === 200) {
                        var shipment = res.extend.shipment;
                        currentShipment = shipment;

                        // 使用doT模板渲染确认发货界面
                        var html = confirmShipmentTmpl(shipment);
                        $('#confirmShipmentContent').html(html);

                        $('#confirmShipmentDlg').dialog('open').dialog('setTitle', '确认发货').window('center');
                    } else {
                        $.messager.alert('错误', res.msg || '获取发货单详情失败!', 'error');
                    }
                }
            });
        }

        // 确认发货
        function confirmShipment() {
            if (!currentShipment || !currentShipment.id) {
                $.messager.alert('错误', '发货单信息不完整!', 'error');
                return;
            }

            $.ajax({
                url: 'shipment/confirm/' + currentShipment.id,
                type: 'put',
                dataType: 'json',
                success: function(res) {
                    if (res.code === 200) {
                        $.messager.show({
                            title: '成功',
                            msg: '发货成功!',
                            timeout: 2000,
                            showType: 'slide'
                        });

                        $('#confirmShipmentDlg').dialog('close');
                        $('#datagrid').datagrid('reload');
                    } else {
                        $.messager.alert('错误', res.msg || '确认发货失败!', 'error');
                    }
                }
            });
        }
    </script>
</body>
</html>
